package study.thread.atomic;

/*
 * 模拟取钱未同步出现的错误
 */
public class Account {
	private double balance;

	public Account(double money) {
		this.balance = money;
		System.out.println("Total Money: " + balance);
	}

	public void deposit(double money) {
		balance += money;
	}

	//不用synchronized同步方法，业务逻辑就会出问题
	public void withdraw(double money, int delay) {
		if (balance >= money) {
			try {
				//使当前线程睡眠delay毫秒
				Thread.sleep(delay);
				balance = balance - money;
				System.out.println(Thread.currentThread().getName()
						+ " withdraw  " + money + " successful!" + balance);
			} catch (InterruptedException e) {
			}
		} else
			System.out.println(Thread.currentThread().getName()
					+ " balance is not enough, withdraw failed!" + balance);
	}
}
